package cn.zhejianglao.shirotemplate.config.shiro;

import cn.zhejianglao.shirotemplate.common.model.PermissionVO;
import cn.zhejianglao.shirotemplate.common.model.RoleVO;
import cn.zhejianglao.shirotemplate.common.model.UserVO;
import cn.zhejianglao.shirotemplate.service.permission.dao.IPermissionMapper;
import cn.zhejianglao.shirotemplate.service.role.dao.IRoleMapper;
import cn.zhejianglao.shirotemplate.service.user.dao.IUserMapper;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;


/**
 * one of the shiro core components
 */
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private IUserMapper userMapper;

    @Autowired
    private IRoleMapper roleMapper;

    @Autowired
    private IPermissionMapper permissionMapper;

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken)
            throws AuthenticationException {
        if (authenticationToken == null) {
            return null;
        }
        String username = authenticationToken.getPrincipal().toString();
        if (userMapper.selectCountByUsername(username) != 0) {
            UserVO userVO = userMapper.selectByUsername(username);
            return new SimpleAuthenticationInfo(username, userVO.getPassword(), userVO.getUsername());
        }
        return null;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String userName = (String) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        // 从数据库获取角色
        List<RoleVO> roleVOList = roleMapper.selectRolesByUsername(userName);
        // 获取用户当前角色
        final Long currentRoleId = userMapper.selectCurrentRoleIdByUsername(userName);
        Long selectedRoleId;
        // 如果当前角色在所有角色中，那么就使用该角色
        if (roleVOList.stream().anyMatch(role -> role.getId().equals(currentRoleId))) {
            selectedRoleId = currentRoleId;
        } else {
            // 否则使用列表中的第一个角色
            selectedRoleId = roleVOList.get(0).getId();
        }
        // 获取角色名称
        String selectedRoleName = roleMapper.selectById(selectedRoleId).getRoleName();
        Set<String> roles = new HashSet<>();
        roles.add(selectedRoleName);
        simpleAuthorizationInfo.setRoles(roles);
        userMapper.updateCurrentRoleIdToFirstByUsername(userName, selectedRoleId);
        // 获取所有权限
        Set<String> permissions = permissionMapper.selectPermissionsByRoleId(selectedRoleId)
                .stream()
                .map(PermissionVO::getPermissionName)
                .collect(Collectors.toSet());
        simpleAuthorizationInfo.setStringPermissions(permissions);
        return simpleAuthorizationInfo;
    }

}
